<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017-10-19
 * Time: 15:00
 */
namespace App\Http\Biz;

use App\Http\Model\ConsoleAccountRole;
use App\Http\Model\PtGoods;
use App\Http\Model\PtGoodsOrderMid;
use App\Http\Model\PtGoodsSpec;
use App\Http\Model\PtMaterial;
use App\Http\Model\PtPreSale;
use App\Http\Model\Shop;
use App\Http\Model\ShopAccount;
use App\Http\Model\ShopAccountRoleMid;
use App\Http\Model\ShopAddGoods;
use App\Http\Model\ShopAddGoodsMid;
use App\Http\Model\ShopGoods;
use App\Http\Model\ShopGoodsGroup;
use App\Http\Model\ShopGoodsGroupMid;
use App\Http\Model\ShopGoodsInoutMid;
use App\Http\Model\ShopGoodsOrderMid;
use App\Http\Model\ShopModule;
use App\Http\Model\ShopOrder;
use App\Http\Model\ShopRole;
use App\Http\Model\ShopRoleModuleMid;
use App\Http\Model\ShopSupp;
use App\Http\Model\ShopSuppProtocolMid;
use App\Http\Model\ShopTorage;
use App\Http\Model\ShopTorageInOut;
use App\Http\Model\Supp;
use App\Http\Model\SuppGoodsMid;
use App\Http\Model\SuppReport;
use App\Http\Utils\Common\Consts;
use App\Http\Utils\Common\RoleUtils;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\DB;
use PDOException;
use Log;

class SuppReportBiz
{
    //根据供应商id查询所有商品
    public function getGoodsBySuppIdBiz($supp_id)
    {
        try {
            Log::debug(get_class($this) . ' ' . __FUNCTION__ . ' ' . 'start');
            DB::enableQueryLog();
            $now = Carbon::now();
            Log::info($now);
            //1，查询规格表的所有供应商商品goods_id
            $goods_ids = PtGoodsSpec::where('supp_id',$supp_id)->pluck('goods_id')->all();
            Log::info('----$goods_ids------');
            Log::info($goods_ids);
            //能够上报的这期的商品
//            Log::info(PtPreSale::whereIn('goods_id',$goods_ids)->where('start_date','>',$now)->where('end_date','<',$now)->toSql());
            $can_goods_ids = PtPreSale::whereIn('goods_id',$goods_ids)->where('start_date','<',$now)->where('end_date','>',$now)->pluck('goods_id')->all();
            Log::info('----$can_goods_ids------');
            Log::info($can_goods_ids);
            $goods = PtGoodsSpec::whereIn('goods_id',$can_goods_ids)->orderBy('goods_id')->where('supp_id',$supp_id)->get(['name as spec_name','id as spec_id','goods_id']);
            foreach ($goods as $good){
                $tmp = PtPreSale::where('goods_id',$good->goods_id)->where('start_date','<',$now)->where('end_date','>',$now)->first();
                if($tmp!=null){
                    $good->nper = '期数'.date('Y-m-d H:i',strtotime($tmp->start_date)).'~'.date('Y-m-d H:i',strtotime($tmp->end_date));
                    $good->nper_id = $tmp->id;
                }else{
                    $good->nper = null;
                    $good->nper_id = null;
                }
                $good->goods_name = PtGoods::find($good->goods_id)->goods_name;
            }
            return $goods;
//            $groups = array();
////            $goods_ids = SuppGoodsMid::where('supp_id',$supp_id)->pluck('goods_id')->all();
//            $goods_ids = PtGoodsSpec::select(DB::raw('distinct(goods_id) as goods_id'))->where('supp_id',$supp_id)->pluck('goods_id')->all();
//            if(count($goods_ids) > 0){
//                $group_ids = ShopGoodsGroupMid::whereIn('goods_id',$goods_ids)->pluck('group_id')->all();
//                if(count($group_ids) > 0){
//                    $groups = ShopGoodsGroup::whereIn('id',$group_ids)->whereNull('shop_id')->orderBy('seq','asc')->get(['name as group_name','id']);
//                    $now = Carbon::now();
//                    foreach ($groups as $group){
//                        $ids = ShopGoodsGroupMid::where('group_id',$group->id)->pluck('goods_id')->all();
//                        $arr = array_intersect($ids,$goods_ids);
////                        $goods = PtGoods::whereIn('id',$arr)->whereNull('shop_id')->whereIn('goods_type',[1,2])->get(['id','goods_name']);
//                        //商品名称，id，规格id，规格名称
//                        $goods = PtGoodsSpec::query()
//                            ->leftJoin('pt_goods','pt_goods.id','=','pt_goods_spec.goods_id')
//                            ->orderBy('pt_goods.goods_name')
//                            ->whereIn('pt_goods_spec.goods_id',$arr)
//                            ->whereNull('pt_goods.shop_id')
//                            ->where('supp_id',$supp_id)
//                            ->whereIn('pt_goods.goods_type',[1,2])
//                            ->get(['pt_goods.id','pt_goods.goods_name','shop_torage.spec_id','pt_goods_spec.name as spec_name']);
//                        foreach ($goods as $good){
//                            $tmp = PtPreSale::where('goods_id',$good)->where('start_date','>',$now)->where('end_date','<',$now)->first();
//                            if($tmp!=null){
//                                $good->nper = '期数'.date('Y-m-d H:i',strtotime($tmp->start_date)).'~'.date('Y-m-d H:i',strtotime($tmp->end_date));
//                                $good->nper_id = $tmp->id;
//                            }else{
//                                $good->nper = null;
//                                $good->nper_id = null;
//                            }
////                            $good->nper = PtPreSale::where(['goods_id'=>$good->id])->where('end_date','>=',$time)->get(['id','start_date','end_date']);
//                        }
//                        $group->goods = $goods;
//                    }
//                }
//            }
            Log::debug(get_class($this) . ' ' . __FUNCTION__ . ' ' . 'end');
            return $groups;
        } catch (PDOException $ex) {
            Log::error(get_class($this) . ' exception ' . print_r($ex->getMessage(), true));
            return [];
        }
    }




    //根据供应商id查询所有商品
    public function readGoodsByCondition($supp_id,$where,$account_id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            $result=array();
            $ptGoods=PtGoods::query();

            //数据权限
            $role_ids = ConsoleAccountRole::where(['account_id'=>$account_id,'ownto_id'=>$supp_id,'account_types'=>1])->pluck('role_id')->all();
            if(count($role_ids) == 0){
                return null;
            }
            $role_ids = array_intersect($role_ids,Consts::admin_role_supp_sub);//去数组的交集
            if(count($role_ids)>0){
                $goods_ids = RoleUtils::getRightData($account_id,$supp_id,1);
                Log::info($goods_ids);
                $ptGoods = $ptGoods->whereIn('id',$goods_ids);
            }

            $goods_name=null;
            if(array_key_exists('goods_name',$where)){
                if($where['goods_name']!=''){
                    $goods_name=$where['goods_name'];
                }
            }
            if($goods_name!=null){
                $ptGoods->where('goods_name','like','%'.$goods_name.'%');
            }

            $result=$ptGoods->has('PtGoodsSpec')->select('id','goods_name')
                ->with(['PtGoodsSpec' => function ($query) {
                    $query->select('id','name','goods_id');
                }])
                ->where('creator_ownto_id',$supp_id)->orderBy('id','desc')->paginate(Consts::PAGE_SIZE);

            if($result->count()==0){
                return null;
            }
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return $result;
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }



    //根据goods_id查询商品的规格信息
    public function getSpecMsgByGoodsId($id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            $result=array();

            $result=PtGoodsSpec::where('goods_id',$id)->select('id','name','goods_id','stock_num as num')->get();

            if($result->count()==0){
                return null;
            }
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return $result;
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }
    
    
    
    

    //上报数据的时候把这一期的id覆盖规格表
    public function reportNumBiz($supp_id,$params)
    {
        try {
            Log::debug(get_class($this) . ' ' . __FUNCTION__ . ' ' . 'start');
            DB::beginTransaction();
            $arr = [];
            foreach ($params as $item){
                array_push($arr,$item['goods_id']);
                $item['supp_id'] = $supp_id;
                if(empty($item['num'])){
                    $item['num'] = 0;
                }
                SuppReport::create($item);
                //只管根据spec_id往库存表的剩余数量修改值,
                PtGoodsSpec::where('id',$item['spec_id'])->update(['stock_num'=>$item['num']]);
//                $spec->increment('stock_num',$item['num']);
//                $spec->report_pre_sale_id = $item['sale_id'];
//                $spec->save();
            }
            //计算商品总库存数量
            $only_goods_ids = array_unique($arr);
            foreach ($only_goods_ids as $only_goods_id){
                $total_num = PtGoodsSpec::where('goods_id',$only_goods_id)->where('is_online',0)->sum('stock_num');
                PtGoods::where('id',$only_goods_id)->update(['total_stock_num'=>$total_num]);
            }

            Log::debug(get_class($this) . ' ' . __FUNCTION__ . ' ' . 'end');
            DB::commit();
        } catch (PDOException $ex) {
            Log::error(get_class($this) . ' exception ' . print_r($ex->getMessage(), true));
            DB::rollBack();
        }
    }
}